package Component

import (
	"fmt"
	"github.com/pkg/sftp"
	"golang.org/x/crypto/ssh"
	"io"
	"log"
	"os"
	"time"
)

type UploadFileComponent struct {
	remoteServer string
	remotePath   string
	localPath    string

	userName string
	password string
}

func (self *UploadFileComponent) Run() (err error) {
	sshConfig := &ssh.ClientConfig{
		User: self.userName,
		Auth: []ssh.AuthMethod{
			ssh.Password(self.password),
		},
		HostKeyCallback: ssh.InsecureIgnoreHostKey(),
		ClientVersion:   "",
		Timeout:         10 * time.Second,
	}

	sshClient, err := ssh.Dial("tcp", self.remoteServer, sshConfig)
	if err != nil {
		return
	}
	defer sshClient.Close()

	sftpClient, err := sftp.NewClient(sshClient)
	if err != nil {
		return
	}

	defer sftpClient.Close()

	remoteFile, err := sftpClient.Create(self.remotePath)
	if err != nil {
		log.Fatalln(err.Error())
	}
	defer remoteFile.Close()

	fmt.Printf("%s=>%s:%s\r\n", self.localPath, self.remoteServer, self.remotePath)

	//打开本地文件file.dat
	localFile, err := os.Open(self.localPath)
	if err != nil {
		return
	}
	defer localFile.Close()

	//本地文件流拷贝到上传文件流
	_, err = io.Copy(remoteFile, localFile)
	if err != nil {
		return
	}

	return
}

func (self *UploadFileComponent) SetParameter(name string, parameter string) {
	if name == UserName {
		self.userName = parameter
	} else if name == PassWord {
		self.password = parameter
	} else if name == RmoteServer {
		self.remoteServer = parameter
	} else if name == RmotePath {
		self.remotePath = parameter
	} else if name == LocalPath {
		self.localPath = parameter
	}
}
